//
//  OrderDetailViewController.m
//  didacar
//
//  Created by 度周末网络-王腾 on 16/1/11.
//  Copyright © 2016年 dzmmac. All rights reserved.
//

#import "OrderDetailViewController.h"
#import "OrderDetailTopCell.h"
#import "OrderDetailMiddleCell.h"
#import "BottomView.h"
#import "RoutePlanningViewController.h"
#import "OrderDetailRefundTicketCell.h"
#import "TableFoorterView.h"
#import "PayTicketViewController.h"
#import "WXApiManager.h"
#import "PaySuccessViewController.h"
#import "AlipayManager.h"
#import "PayViewModel.h"

@interface OrderDetailViewController () <WXApiManagerDelegate,AlipayManagerDelegate>

@property (nonatomic , strong) PayViewModel *payViewModel;

@property (weak, nonatomic) IBOutlet UITableView *mainTable;

@property (weak, nonatomic) IBOutlet UIView *bottomBGView;

@property (weak, nonatomic) IBOutlet UIView *refuseSectionView;
- (IBAction)refuseSectionAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIImageView *imgArrow;
@property (weak, nonatomic) IBOutlet UILabel *refuseText;

@property (assign, nonatomic) BOOL refundTicketOpen;
@property (strong, nonatomic) TableFoorterView *tableFoorterView;

@property (weak, nonatomic) IBOutlet UIView *footerBg;


@end

@implementation OrderDetailViewController

-(void)awakeFromNib{
    self.orderDetailViewModel = [[OrderDetailViewModel alloc ] init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.payViewModel = [[PayViewModel alloc ] init];
    [WXApiManager sharedManager].delegate = self;
    [AlipayManager sharedManager].delegate = self;
    
    
    self.navigationItem.title = @"订单详情";
    
    [self setLeftBtnItem];
    
    [self setExtraCellLineHidden:self.mainTable];
    
    self.mainTable.alpha = 0;
    self.bottomBGView.alpha = 0;
    
    UIView *bottomLine = [CommoneTools createLineWithFrame:CGRectMake(0, 0, [UIScreen width], 0.45)];
    [self.refuseSectionView addSubview:bottomLine];
    
    
    UIView *topLine = [CommoneTools createLineWithFrame:CGRectMake(0, 43.5, [UIScreen width], 0.45)];
    [self.refuseSectionView addSubview:topLine];
    [SVProgressHUD show];
    [self loadDetailData];

    

}

-(void)loadDetailData{
    
    // 获取班车详情信息
    if (self.isRegularBus) {
        [self loadRegularBusData];
    }else{
        [self loadThroughBusData];
    }
}

/**
 *  获取班车详情信息
 */
-(void)loadThroughBusData{
    WEAKSELF
    [self.orderDetailViewModel getOrderDetailThroughBusData:^(NSInteger resultType, id data, NSString *errorMsg) {
        if (resultType == 1) {
         
            
            [weakSelf success];
        }else{
            [SVProgressHUD showErrorWithStatus:errorMsg];
        }
    }];
}

-(void)success{
    self.mainTable.alpha = 1;
    self.bottomBGView.alpha = 1;
    [self.mainTable reloadData];
    
    [self createBottomBtn];
    
    [self loadCanlender];
}

/**
 *  获取班车详情信息
 */
-(void)loadRegularBusData{
    
    WEAKSELF
    [self.orderDetailViewModel getOrderDetailRegularBusData:^(NSInteger resultType, id data, NSString *errorMsg) {
          [SVProgressHUD dismiss];
        if (resultType == 1) {
           [weakSelf success];
        }else{
            [SVProgressHUD showErrorWithStatus:errorMsg];
        }
    }];
}

-(void)loadCanlender{
    // 日历
    
    WEAKSELF
    dispatch_async(dispatch_get_main_queue(), ^{
        weakSelf.tableFoorterView = [[TableFoorterView alloc ] initWithFrame:CGRectMake(0, 40, [UIScreen width], 0)];
        
        
        NSMutableArray *canlenderList = [weakSelf.orderDetailViewModel getThroughBusLineDateList];
        
        if (canlenderList.count == 0) {
            return ;
        }
        CGFloat height = [weakSelf.tableFoorterView setDataSource:canlenderList];
        [weakSelf.footerBg addSubview:weakSelf.tableFoorterView];
        
        weakSelf.tableFoorterView.frame = CGRectMake(0, 40, [UIScreen width], height);
        weakSelf.footerBg.frame = CGRectMake(0, 0, [UIScreen width], height+ 40);
        weakSelf.mainTable.tableFooterView = weakSelf.footerBg;
        weakSelf.tableFoorterView.dayTicket.isDetail = YES;
       
        
        UIView *bottomLine = [CommoneTools createLineWithFrame:CGRectMake(0, 39.5, [UIScreen width], 0.45)];
        weakSelf.tableFoorterView.dayTicket.calendarblock  = ^void(CalendarDayModel *model){
            
            
            if (model.style == CellDayTypeClick) {
                [weakSelf.orderDetailViewModel.dayRefundTickets addObject:model];
            }else{
                [weakSelf.orderDetailViewModel.dayRefundTickets removeObject:model];
            }
        };
        
        [weakSelf.footerBg addSubview:bottomLine];
    });
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.orderDetailViewModel.orderDetailRegularBusModel.refundTicketList.count > 0) {
        return 3;
    }
    return 2 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 1;
    }else{
        if (self.refundTicketOpen) {
            return self.orderDetailViewModel.orderDetailRegularBusModel.refundTicketList.count;
        }else{
            return 0;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ) {
        return 160;
    }else if (indexPath.section == 1){
        return 130;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 0.01;
    }
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return [[UIView alloc ] initWithFrame:CGRectMake(0, 0, [UIScreen width], 0.01)];
    }
    
    if (self.refundTicketOpen) {
        self.imgArrow.transform=CGAffineTransformMakeRotation(-M_PI/2);
    }else{
        self.imgArrow.transform=CGAffineTransformIdentity;
    }
    self.refuseText.text = [NSString stringWithFormat:@"退票记录:%@次",@(self.orderDetailViewModel.orderDetailRegularBusModel.refundTicketList.count).stringValue];
    return self.refuseSectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        OrderDetailTopCell *topCell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailTopCell"];
        [topCell setOrderDetailRegularBusModel:self.orderDetailViewModel.orderDetailRegularBusModel];
        if (self.isRegularBus) {
            topCell.orderType.text = @"班车";
        }else{
            topCell.orderType.text = @"直通车";
        }
        return topCell;
    }else if (indexPath.section == 1){
        OrderDetailMiddleCell *topCell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailMiddleCell"];
        [topCell setOrderDetailRegularBusModel:self.orderDetailViewModel.orderDetailRegularBusModel];
        return topCell;
    }else{
        
        OrderDetailRefundTicketCell *topCell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailRefundTicketCell"];
        topCell.isThrough = self.isRegularBus;
        [topCell showModel:self.orderDetailViewModel.orderDetailRegularBusModel.refundTicketList[indexPath.row]];
        return topCell;
    }
}

#pragma mark ---------------下方按钮------------------
-(void)createBottomBtn{
    
    NSMutableArray *bottomList = [[NSMutableArray alloc ] init];
    
    // 已支付
    if (self.orderDetailViewModel.orderDetailRegularBusModel.PayStatus == 1) {
        [bottomList addObject:@"退款"];
        [bottomList addObject:@"再次购票"];
    }else if (self.orderDetailViewModel.orderDetailRegularBusModel.PayStatus == 2){
        [bottomList addObject:@"立即支付"];
        [bottomList addObject:@"取消"];
    }else{
        [bottomList addObject:@"再次购票"];
    }
  
    
    WEAKSELF
    BottomView *bottomView = [[BottomView alloc ] initWithStatusArray:bottomList callBlcok:^(NSInteger index) {
        // 已支付
        if (weakSelf.orderDetailViewModel.orderDetailRegularBusModel.PayStatus == 1) {
            
            // 退款
            if (index == 0) {
                
                if (weakSelf.orderDetailViewModel.dayRefundTickets.count == 0) {
                    [SVProgressHUD showErrorWithStatus:@"请选择退票日" duration:1];
                    return ;
                }
                
                [weakSelf.orderDetailViewModel refundTicket:^(NSInteger resultType, id data, NSString *errorMsg) {
                    if (resultType == 1) {
                        [SVProgressHUD showErrorWithStatus:@"退款成功" duration:1];
              
                        [weakSelf loadDetailData];
                    }else{
                        [SVProgressHUD showErrorWithStatus:errorMsg];
                    }
                }];
            }
          
            // 再次购票
            else{
                [weakSelf bugTicket];
            }
        }  // 立即支付
        else if (self.orderDetailViewModel.orderDetailRegularBusModel.PayStatus == 2){
             if (index == 0) {
                  [self pay];
             }
            // 再次购票
            else{
                [weakSelf cancelOrder];
            }
           
        }
        // 再次购票
        else{
            [weakSelf bugTicket];
        }
    }];
    [self.bottomBGView addSubview:bottomView];
}

-(void)cancelOrder{
    
    WEAKSELF
    [self.orderDetailViewModel cancelOrder:^(NSInteger resultType, id data, NSString *errorMsg) {
        if (resultType == 1) {
            if (resultType == 1) {
                [SVProgressHUD showErrorWithStatus:@"取消成功" duration:1];
                [weakSelf loadDetailData];
            }else{
                [SVProgressHUD showErrorWithStatus:errorMsg];
            }
        }
        
    }];
}

-(void)pay{

    self.payViewModel.PayChannel = self.orderDetailViewModel.orderDetailRegularBusModel.PayType;
    self.payViewModel.OrderNumber = self.orderDetailViewModel.orderDetailRegularBusModel.TicketOrderNum;
    
    WEAKSELF
    [self.payViewModel getPayMsg:^(NSInteger resultType, id data, NSString *errorMsg) {
        
        
        if (resultType == 1) {
            NSInteger status = [[weakSelf.payViewModel.responseDic objectForKey:@"PayStatus"] integerValue];
            //代表已支付
            if (status == 3) {
                [weakSelf paySuccess];
            }else if (status == 1 && [weakSelf.payViewModel.responseDic objectForKey:@"PayInfo"]!= nil){
                
                if (weakSelf.orderDetailViewModel.orderDetailRegularBusModel.PayType == 1) {
                    [[AlipayManager sharedManager] alipaySdk:[weakSelf.payViewModel.responseDic objectForKey:@"PayInfo"]];
                }else{
                    
                    [[WXApiManager sharedManager] wxPaySdk:[weakSelf.payViewModel.responseDic objectForKey:@"PayInfo"]];
                }
                
            }else{
                [SVProgressHUD showErrorWithStatus:errorMsg];
            }
        }else{
            [SVProgressHUD showErrorWithStatus:errorMsg];
        }
    }];
}

-(void)wxPayRespSuccess{
    [self paySuccess];
}

-(void)alipayPayRespSuccess{
    [self paySuccess];
}

-(void)paySuccess{
    PaySuccessViewController *paySuccess = [[UIStoryboard storyboardWithName:@"Ticket" bundle:nil]  instantiateViewControllerWithIdentifier:@"PaySuccessViewController"];
    paySuccess.price = self.orderDetailViewModel.orderDetailRegularBusModel.TicketOrderPrice.stringValue;
    [self.navigationController pushViewController:paySuccess animated:YES];
}

// 再次购票
-(void)bugTicket{
    RoutePlanningViewController *routePlanningViewController = (RoutePlanningViewController *)[RoutePlanningViewController getViewControllerFromSbName:@"RoutePlanning" viewControllerName:@"RoutePlanningViewController"];
    
    if (self.orderDetailViewModel.orderDetailRegularBusModel.LineType == 1) {
        routePlanningViewController.routePlanningStatus = RoutePlanningSuccess;
    }else{
        routePlanningViewController.routePlanningStatus = RoutePlanningThroughBus;
    }
    
    
  
    routePlanningViewController.lineId = @(self.orderDetailViewModel.orderDetailRegularBusModel.LineId).stringValue;
    routePlanningViewController.StartStationId = self.orderDetailViewModel.orderDetailRegularBusModel.StartId;
    routePlanningViewController.EndStationId  = self.orderDetailViewModel.orderDetailRegularBusModel.EndId;
    routePlanningViewController.BCID = self.orderDetailViewModel.orderDetailRegularBusModel.BCID;
    [self.navigationController pushViewController:routePlanningViewController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

// 展开和合上退票记录
- (IBAction)refuseSectionAction:(UIButton *)sender {
    self.refundTicketOpen = !self.refundTicketOpen;
    [self.mainTable reloadData];
}
@end
